class BaseMonitor {
  constructor(deviceId, mqttConnector) {
    this.deviceId = deviceId;
    this.mqttConnector = mqttConnector;
    this.topics = {};
    this.callbacks = {};
  }

  // 订阅主题
  async subscribe(topics) {
    if (!Array.isArray(topics)) {
      topics = [topics];
    }

    for (const topic of topics) {
      await this.mqttConnector.subscribe(topic);
      this.topics[topic] = true;
    }
  }

  // 发布消息
  async publish(topic, message) {
    return this.mqttConnector.publish(topic, message);
  }

  // 注册消息处理回调
  onMessage(topic, callback) {
    if (!this.callbacks[topic]) {
      this.callbacks[topic] = [];
    }
    this.callbacks[topic].push(callback);
  }

  // 处理接收到的消息
  handleMessage(topic, message) {
    if (this.callbacks[topic]) {
      for (const callback of this.callbacks[topic]) {
        try {
          callback(message);
        } catch (error) {
          console.error(`处理消息回调错误: ${error.message}`);
        }
      }
    }
  }

  // 清理资源
  async cleanup() {
    // 取消订阅所有主题
    for (const topic in this.topics) {
      await this.mqttConnector.unsubscribe(topic);
    }
    this.topics = {};
    this.callbacks = {};
  }
}

module.exports = BaseMonitor;